﻿using Autofac;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using Wicture.DbRESTFul;
using Wicture.DbRESTFul.Auth;
using Wicture.DbRESTFul.Cache;
using Wicture.DbRESTFul.ObjectContainers;
using Wicture.DbRESTFul.SQL;
using Wicture.Microservice;
using Wicture.Microservice.DbProviders;
using Wicture.QPZS.EPC.API.DockerDbGatewayTest;
using Wicture.QPZS.EPC.API.Domain;

namespace Wicture.QPZS.EPC.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMvc(options => options.Filters.Add(new ApiExceptionFilterAttribute()));

            services.AddMemoryCache();

            var tokenProviderOptions = TokenProviderOptions.Default;
            tokenProviderOptions.Expiration = TimeSpan.FromHours(24);
            tokenProviderOptions.TokenRequestPath = "/auth";

            services.AddSingleton(services.AddJwtTokenAuthorization(authIdentifier: new DefaultRepository(), tokenProviderOptions: tokenProviderOptions));

            services.UseMicroservice(Configuration)
                    .UseCache();

            var serviceProvider = services.UseAutofacContainer(typeof(Startup).Assembly, typeof(IMicroserviceDbGateway).Assembly);

            var dbGateway = AutofacContainer.Current.Resolve<IEpcApiDbGateway>();

            services.UseSQLStorage(dbGateway);
            return serviceProvider;
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());

            app.UseMicroservice(routeSetting: new RouteSetting(new List<string> { "/auth" }));

            app.UseApiServices();

            app.UseMvc();
        }
    }
}
